package com.mama100.rpc.mdp.job;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.mama100.coupon.inout.CouponConditionEnum;
import com.mama100.coupon.inout.CouponIssueInfo;
import com.mama100.rpc.mdp.service.ICouponService;

/**
 * 
 * 
 * @author 10747
 */
@Service("couponDbJob")
public class CouponDbJob {

	protected Logger log = LoggerFactory.getLogger(this.getClass());

	@Resource(name = "racJdbcTemplate")
	JdbcTemplate jdbcTemplate;

	@Resource
	private ICouponService icouponService;

	public void exec() {
		log.info("start CouponDbJob !");
		String sql = "select * from mama100_owner.MDP_COUPON_SEND_TASK where status = 0 ";
		List<Map<String, Object>> ls = jdbcTemplate.queryForList(sql);
		for (Map<String, Object> m : ls) {
			
			Long id = ((BigDecimal) m.get("id")).longValue();
			Long customerId = ((BigDecimal) m.get("customer_id")).longValue();
			
			String couponDefIdStr =  (String) m.get("coupon_def_id_str");
			String couponConditionValueStr = (String) m.get("coupon_condidion_value_str");
			
			log.info("return couponDefId:{},couponConditionValue:{}", couponDefIdStr, couponConditionValueStr);
			if (couponDefIdStr != null && couponConditionValueStr != null) {
				String[] couponDefIds = couponDefIdStr.split(",");
				String[] couponConditionValues = couponConditionValueStr.split(",");
				if(couponDefIds.length > 0 && couponDefIds.length == couponConditionValues.length){
					List<CouponIssueInfo> infos = new ArrayList<CouponIssueInfo>();
					
					for(int i=0;i<couponDefIds.length;i++){
						Long couponDefId = Long.parseLong(couponDefIds[i]);
						
						CouponIssueInfo info = new CouponIssueInfo();
						//优惠券定义ID
						info.setCouponDefId(couponDefId);
						//发行方式对应的值
						info.setCouponConditionValue(couponConditionValues[i]);
						//优惠券发行方式：1-送出,2-花钱买,3-积分兑,4-参加活动（枚举）
						info.setCouponCondition(CouponConditionEnum.CAMPAIGN);
						//平台渠道：-1-全部，1-在线支付，3、支付宝，4-微信支付
						//info.setPlatformChannel(platformChannel);
						
						infos.add(info);
					}
					
					try {
						//批量发送
						icouponService.sendbatchCoupin(customerId, infos);
						updateTaskStatus(id, 1, null);
					} catch (Throwable e) {
						log.error("send error", e);
						updateTaskStatus(id, 2, StringUtils.substring(e.getMessage(), 0, 2000));
					}
				}
			}
		}

	}

	private void updateTaskStatus(Long id, int status, String retmsg) {
		try {
			String sql = "update mama100_owner.MDP_COUPON_SEND_TASK set status = ? , retmsg = ? where id = ? ";
			jdbcTemplate.update(sql, status, retmsg, id);
		} catch (DataAccessException e) {
			log.error("update send record error", e);
		}
	}

}
